/**
 * 
 */
package com.tbdgroup.babycare.chart;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.tbdgroup.babycare.R;
import com.tbdgroup.babycare.db.DBManager;
import com.tbdgroup.babycare.db.Event;

/**
 * @author wsf
 * 
 */
public class ChartActivity extends Activity {

	private WebView mWebView;
	
	private DBManager dbManager;

	@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chart_view);
		dbManager = new DBManager(this);
		
		mWebView = (WebView) findViewById(R.id.webView);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.requestFocus();
		mWebView.setWebChromeClient(new WebChromeClient());
		mWebView.addJavascriptInterface(new SelfWebAppInterface(this, dbManager), "dataObject");
		mWebView.loadUrl("file:///android_asset/index.html");
		mWebView.setWebViewClient(new SelfWebViewClient());
	}
	
}

class SelfWebAppInterface {
	Context mContext;
	
	private DBManager dbManager;

	SelfWebAppInterface(Context c, DBManager dbManager) {
        mContext = c;
        this.dbManager = dbManager;
    }

    @JavascriptInterface
    public void getDataJson() {
    	List<Event> events = dbManager.getAllEvent();
    	JSONObject result = new JSONObject();

    	for(Event e : events) {
    		if(e != null) {
    			String type = e.type;
				try {
					result.accumulate(type, type);
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
    		}
    	}
    	
    	String str = result.toString();
    	System.out.println(str);
    }
}

class SelfWebViewClient extends WebViewClient {
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		view.loadUrl(url);
		return true;
	}

	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		super.onPageStarted(view, url, favicon);
	}

	@Override
	public void onPageFinished(WebView view, String url) {
		super.onPageFinished(view, url);
	}

	public void onReceivedError(WebView view, int errorCode,
			String description, String failingUrl) {
		super.onReceivedError(view, errorCode, description, failingUrl);
	}
}
